var $customerTable = $('#customerTableList');//客户清单
var rowCustomerId;
//防止表头与表格不对齐
$(window).resize(function () {
    $customerTable.bootstrapTable('resetView');
});

$(function () {
    var isAdmin = JSON.parse($("#isAdmin").val());
    customerTableListInit(isAdmin);

    /* 高级筛选 */
    $('#filterContent').on('show.bs.collapse', function () {
        $('.btn-senior').html('<i class="mdi mdi-close"></i>关闭筛选');
    }).on('hide.bs.collapse', function () {
        $('.btn-senior').html('<i class="mdi mdi-sort-variant"></i>高级筛选');
    }).on('hidden.bs.collapse', function () {
        resetData('#filterContent');
    });
    $('.filter-content select').selectpicker({
        noneSelectedText: '请选择',
        sanitize: true,
        size: 8
    });
    $('.custom-group input[type="checkbox"]').click('click', function () {
        let customGroup = $(this).parents('.custom-group');
        if ($(this).prop('checked')) {
            // 自定义条件筛选
            customGroup.addClass('custom-active');
            customGroup.find('select').attr('disabled', 'disabled').find('option:first').prop('selected', 'selected');
            customGroup.find('select').selectpicker('refresh');
        } else {
            // 默认条件筛选
            customGroup.removeClass('custom-active');
            customGroup.find('select').removeAttr('disabled').selectpicker('refresh');
            $(this).parents('.custom-box').find('input[type="text"]').val('');
        }
    });
});

/**
 * 客户清单
 */
function customerTableListInit(flag) {
    $customerTable.bootstrapTable('destroy');//先销毁表格
    $customerTable.bootstrapTable({
        classes: 'table table-hover table-noborder',
        url: '/customerController/customerList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'customerId',
        idField: 'customerId',
        pageSize: globalPageSize,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: globalPageList,//可供选择的每页的行数
        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'customerId', visible: false},
            /*{title: '全选', field: 'checked', align: 'center', checkbox: true, valign: 'middle', width: '6%'},*/
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '60', formatter: indexFormat},
            {title: '客户名称', field: 'customerName', align: 'left', valign: 'middle'},
            {title: '所在地区', field: 'provinceName', align: 'left', valign: 'middle'},
            {title: '创建时间', field: 'createTm', align: 'center', valign: 'middle'},
            {title: '客户级别', field: 'customerLevel', align: 'right', valign: 'middle', width: '100',},
            {title: '标签', field: 'tag', align: 'center', valign: 'middle'},
            /*{title: '联系人数量', field: 'contactPersonCount', align: 'right', valign: 'middle', width: '100'},
            {title: '跟进次数', field: 'followCount', align: 'right', valign: 'middle', width: '100'},*/
            {title: '客户类型', field: 'customerType', align: 'right', valign: 'middle', width: '80', formatter: customerTypeFormat},
            {title: '目前状态', field: 'currentStatus', align: 'right', valign: 'middle', width: '100', formatter: currentStatusFormat},
            {title: '操作', field: 'operate', visible: flag, align: 'right', events: operateEvents, formatter: genderOpt}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
        rowStyle: function(row, index) {
            var num = index.toString();
            var classes = ['active', 'success', 'info', 'warning', 'danger'];
            if (index % 2 === 0 && index / 2 < index) {
                return {classes: classes[num.substring(num.length-1) / 2]};
            }
            return {};
        }
    });
}

/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}

/**
 * 拼接客户表格查询条件参数
 * @param params
 * @returns {*}
 */
function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式

    //普通搜索条件
    params.customerPoolId = $('#customerPoolId').val();
    params.customerName = $.trim($('#customerName').val());
    return params;
}

/**
 * 搜索点击事件
 */
function searchCustomerTableList(type){
    if (type == 1) {//普通搜索点击事件
        $customerTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
        // 点击搜索重置表单 需传入高级搜索id #filterContent
        resetData('#filterContent');
        $('#filterContent').collapse('hide');
    } else {//高级搜索点击事件
        $customerTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: advancedQueryParams});
    }
}

/**
 * 高级搜索点击事件
 */
function advancedQueryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式

    //清空普通搜索条件
    $('#customerName').val('');

    var industry = $('#industrySelect option:selected').val();//行业
    var companyType = $('#companyTypeSelect option:selected').val();//企业类型

    var yearsEstablishmentSelect = $('#yearsEstablishmentSelect option:selected').val();//成立年限
    /**自定义成立年限**/
    var beginYearsEstablishmentCustom = $('#beginYearsEstablishment').val();
    var endYearsEstablishmentCustom = $('#endYearsEstablishment').val();
    var beginYearsEstablishment;
    var endYearsEstablishment;
    if(yearsEstablishmentSelect == 1){//1年内
        endYearsEstablishment = 0;
    }else if(yearsEstablishmentSelect == 2){//1-3年
        beginYearsEstablishment = 1;
        endYearsEstablishment = 3
    }else if(yearsEstablishmentSelect == 3){//3-5年
        beginYearsEstablishment = 3;
        endYearsEstablishment = 5;
    }else if(yearsEstablishmentSelect == 4){//5-10年
        beginYearsEstablishment = 5;
        endYearsEstablishment = 10;
    }else if(yearsEstablishmentSelect == 5){//10年以上
        beginYearsEstablishment = 11;
    }

    if(beginYearsEstablishmentCustom){
        beginYearsEstablishment = beginYearsEstablishmentCustom;
    }
    if(endYearsEstablishmentCustom){
        endYearsEstablishment = endYearsEstablishmentCustom;
    }

    var registeredCapitalSelect = $('#registeredCapitalSelect option:selected').val();//注册资本
    /**自定以注册资本**/
    var beginRegisteredCapitalCustom = $('#beginRegisteredCapital').val();
    var endRegisteredCapitalCustom = $('#endRegisteredCapital').val();
    var beginRegisteredCapital;
    var endRegisteredCapital;
    if(registeredCapitalSelect){
        if(registeredCapitalSelect == 1){//100万以内
            endRegisteredCapital = 99;
        }else if(registeredCapitalSelect == 2){//100万-500万
            beginRegisteredCapital = 100;
            endRegisteredCapital = 500;
        }else if(registeredCapitalSelect == 3){//500万-1000万
            beginRegisteredCapital = 500;
            endRegisteredCapital = 1000;
        }else if(registeredCapitalSelect == 4){//1000万-3000万
            beginRegisteredCapital = 1000;
            endRegisteredCapital = 3000;
        }else if(registeredCapitalSelect == 5){//3000万-5000万
            beginRegisteredCapital = 3000;
            endRegisteredCapital = 5000;
        }else if(registeredCapitalSelect == 6){//5000万以上
            beginRegisteredCapital = 5001;
        }
    }
    if(beginRegisteredCapitalCustom ){
        beginRegisteredCapital = beginRegisteredCapitalCustom;
    }
    if(endRegisteredCapitalCustom ){
        endRegisteredCapital = endRegisteredCapitalCustom;
    }

    var insuredNumbersSelect = $('#insuredNumbersSelect option:selected').val();//参保人数
    /**自定义参保人数**/
    var beginInsuredNumbersCustom = $('#beginInsuredNumbers').val();
    var endInsuredNumbersCustom = $('#endInsuredNumbers').val();
    var beginInsuredNumbers;
    var endInsuredNumbers;
    if(insuredNumbersSelect){
        if(insuredNumbersSelect == 1){//5人以下
            endInsuredNumbers = 4;
        }else if(insuredNumbersSelect == 2){//5-10人
            beginInsuredNumbers = 5;
            endInsuredNumbers = 10;
        }else if(insuredNumbersSelect == 3){//10-20人
            beginInsuredNumbers = 10;
            endInsuredNumbers = 20;
        }else if(insuredNumbersSelect == 4){//20-100人
            beginInsuredNumbers = 20;
            endInsuredNumbers = 100;
        }else if(insuredNumbersSelect == 5){//100-500人
            beginInsuredNumbers = 100;
            endInsuredNumbers = 500;
        }else if(insuredNumbersSelect == 6){//500-1000人
            beginInsuredNumbers = 500;
            endInsuredNumbers = 1000;
        }else if(insuredNumbersSelect == 7){//1000人以上
            beginInsuredNumbers = 1001;
        }
    }
    if(beginInsuredNumbersCustom ){
        beginInsuredNumbers = beginInsuredNumbersCustom;
    }
    if(endInsuredNumbersCustom ){
        endInsuredNumbers = endInsuredNumbersCustom;
    }

    var contactPersonPhone =  $('#isExistContactPersonPhone option:selected').val();//是否有联系电话
    var contactPerson =  $('#isExistContactPerson option:selected').val();//是否有联系人
    var email =  $('#isExistCompanyEmail option:selected').val();//是否有联系邮箱

    params.customerPoolId = $('#customerPoolId').val();
    params.industry = industry;
    params.companyType = companyType;
    params.beginYearsEstablishment = beginYearsEstablishment;
    params.endYearsEstablishment = endYearsEstablishment;
    params.beginRegisteredCapital = beginRegisteredCapital;
    params.endRegisteredCapital = endRegisteredCapital;
    params.beginInsuredNumbers = beginInsuredNumbers;
    params.endInsuredNumbers = endInsuredNumbers;
    params.contactPersonPhone = contactPersonPhone;
    params.contactPerson = contactPerson;
    params.email = email;
    params.tag = $.trim($('#tag').val());
    params.currentStatus = $('#currentStatusSelect option:selected').val();//目前状态
    params.provinceName = $.trim($('#provinceName').val());
    params.cityName = $.trim($('#cityName').val());
    params.countyName = $.trim($('#countyName').val());
    params.customerType = $('#customerTypeSelect option:selected').val();//客户类型  0企业客户 1个人客户
    return params;
}

/**
 * 目前状态
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function currentStatusFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (0 == value) {
        return "未领取";
    } else if (1 == value) {
        return "已领取";
    } else if (2 == value) {
        return "已分配";
    } else if (3 == value){
        return "自建客户";
    }
}

/**
 * 客户类型(0企业客户 1个人客户)
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function customerTypeFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (0 == value) {
        return "<span class='label label-success-light' style='border-radius: 20px'>企业客户</span>";
    } else if (1 == value) {
        return "<span class='label label-info-light' style='border-radius: 20px'>个人客户</span>";
    }
}

/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    let html = '';
    html += '<a type="button" id="detail" class="btn btn-xs btn-default m-r-5 show-btn" title="查看" data-toggle="tooltip"><i class="mdi mdi-eye"></i></a>';
    html += '<a type="button" id="distribution" class="btn btn-xs btn-default m-r-5 show-btn" title="分配" data-toggle="tooltip"><i class="mdi mdi-account-switch"></i></a>';
    html += '<a type="button" id="retrieve" class="btn btn-xs btn-default m-r-5 show-btn" title="收回" data-toggle="tooltip"><i class="mdi mdi-sync"></i></a>';

    return html;
}

/**
 * 自定义操作列事件
 */
window.operateEvents = {
    //查看点击事件
    'click #detail': function (e, value, row, index) {
        if(row.customerType == 1) {//个人客户
            contactNameDetail(row.customerName,row.contactPersonPhone,row.customerId);
        }else{
            parent.$(parent.document).data('multitabs').create({
                iframe : true,
                title : '客户详情',
                url : "/front/customerManager/customerDetail?customerId=" + row.customerId
            }, true);
        }

    },
    //分配点击事件
    'click #distribution': function (e, value, row, index) {
        var customerPoolId = $("#customerPoolId").val();
        var poolState = $("#poolState").val();
        var nature = $("#nature").val();
        if (poolState == 2) {
            $.alert("客户池已停用不能分配！");
            return;
        }
        var currentStatus = row.currentStatus;
        if (currentStatus == '1') {
            $.alert("客户已领取，不能分配！");
            return;
        } else if (currentStatus == '2') {
            $.alert("客户已分配，不能重复分配！");
            return;
        } else if (currentStatus == '3') {
            $.alert("自建客户，不能分配！");
            return;
        }
        if (currentStatus != '0') {
            $.alert('客户目前状态未处于”未领取“状态，不能分配！');
            return;
        }
        //全国公有池
        if (nature == 1) {
            loadAllCompanyList(); //加载全国公司
        }

        //分公司公有池
        if (nature == 2) {
            loadBranchCompanyList(customerPoolId);
        }
        resetData();
        $("#customerId").val(row.customerId);
        $('#customerDistributeModal').modal('show');
    },
    //收回点击事件
    'click #retrieve': function (e, value, row, index) {
        var currentStatus = row.currentStatus;
        /*if (currentStatus == '3') {
            $.alert("自建客户,不能收回!");
            return;
        }*/
        if (currentStatus == '0') {
            $.alert("客户未领取或分配,不能收回!");
            return;
        }
        $('#returnReason').val('');
        $('#retrieveCustomerModal').modal('show');
        rowCustomerId = row.customerId;
    },
    //删除点击事件
    /*'click #delete': function (e, value, row, index) {
        deleteCustomer(row.customerId, row.currentStatus);
    },*/
};

/**
 * 我的客户(个人客户)--客户名称列点击事件(客户详情)
 * @param customerName
 * @param contactPersonPhone
 */
function contactNameDetail (customerName, contactPersonPhone, customerId) {
    var contactId = "";

    //查询联系人id,进行跳转
    $.ajax({
        url: '/contact/getCustomerIdAndContactNameAndAccountId',
        type: 'POST',
        dataType: "json",
        data: {
            customerId,
            contactName: customerName,
            contactInformation : contactPersonPhone,
            contactNature : '1'
        },
        success: (function (data) {
            if (data.code == "000000") {
                if (data.data.contactId != null) {
                    contactId = data.data.contactId;
                    parent.$(parent.document).data('multitabs').create({
                        iframe: true,
                        title: '联系人详情',
                        url: "/front/user/contactManager/contactDetail?contactId=" + contactId
                    },true);
                }else{
                    $.alert("数据有问题,请重试!");
                }
            } else {
                alert("操作失败");
            }
        }),
        error: (function () {
            alert("失败");
        })
    });
}


/**
 * 客户--删除
 * @param customerId     ---客户主键
 * @param currentStatus  ---目前状态
 */
function deleteCustomer(customerId, currentStatus) {
    if (currentStatus != '0') {
        $.alert("请先收回再删除!");
        return;
    }
    $.alert({
        title: '提示',
        content: "确定要删除吗？",
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.ajax({
                        type: "post",
                        url: "/customerController/deleteCustomer",
                        data: {
                            customerId: customerId
                        },
                        dataType: 'json',
                        success: function (data, status) {
                            if (data.code == '000000') {
                                $.alert('删除成功!');
                                $customerTable.bootstrapTable('refreshOptions', {pageNumber: 1});
                            } else {
                                $.alert('删除失败!');
                            }
                        },
                        error: function () {
                            $.alert('删除异常，请稍后再试!');
                        }
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                }
            }
        }
    })
}

/**
 * 客户--收回
 */
function retrieveCustomer() {
    var returnReason = $('#returnReason').val();//客户收回原因
    if(!returnReason){
        $.alert("收回原因不能为空");
        return;
    }
    $.alert({
        title: '提示',
        content: "确定要收回吗？",
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.ajax({
                        type: "post",
                        url: "/customerController/retrieveCustomer",
                        data: {
                            customerId: rowCustomerId,
                            returnReason:returnReason
                        },
                        dataType: 'json',
                        success: function (data, status) {
                            if (data.code == '000000') {
                                $.alert('收回成功!');
                                $customerTable.bootstrapTable('updateCellById', {
                                    id: rowCustomerId,
                                    field: 'currentStatus',
                                    value: '0'
                                });
                            } else if (data.code == 'CL0001') {//客户已锁定
                                $.alert(data.message);
                            } else {
                                $.alert('收回失败!');
                            }
                        },
                        error: function () {
                            $.alert('收回异常，请稍后再试!');
                        }
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                }
            }
        }
    });
    $('#retrieveCustomerModal').modal('hide');
}

/**
 * 新增客户
 */
/*function addCustomer(){
    var customerPoolId = $('#customerPoolId').val();//客户池主键
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : '新增客户',
        url : "/front/customerManager/addCustomer?customerPoolId=" + customerPoolId
    }, true);
}*/

//下载客户导入模板
function downCustomerTemplate(){
    var url="/customerImport/downloadCustomerTemplate";
    window.location.href=encodeURI(encodeURI(url));
}

//显示导入客户模态框
function showImportCustomerModal(){
    $('#importCustomerModal').modal('show');
}

//取消导入客户模态框
function cancelImportCustomerList() {
    $("#importCustomerFile").val("");
}

//导入客户
/*function importCustomerList() {
    //客户池主键
    var customerPoolId = $("#customerPoolId").val();
    if(!document.getElementById('importCustomerFile').files[0]){
        $.alert({
            title: '温馨提示',
            content: '请选择文件！',
        });
        return;
    }
    var fileName = document.getElementById('importCustomerFile').files[0].name;
    var fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length);
    var formData = new FormData();
    //接口接收参数 键值形式 添加到formData中
    formData.append("file",$("#importCustomerFile")[0].files[0]);
    formData.append("customerPoolId",customerPoolId);
    if(fileName!="" && (fileType.toLocaleUpperCase()==".XLSX" || fileType.toLocaleUpperCase()==".XLS")){
        $.ajax({
            url: '/customerImport/customerImport',
            type: 'POST',
            dataType:"json",
            contentType:false,
            data: formData,
            processData: false,
            success:(function(data) {
                if(data.code == "000000"){
                    //客户导入数量
                    var importCustomerNum = data.data.importCustomerNum;
                    var repeatIdStr = data.data.repeatIdStr;
                    var importFailIdStr = data.data.importFailIdStr;

                    //返回内容
                    var content = "";

                    //导入数量大于0
                    if(importCustomerNum>0){
                        content = "成功导入"+importCustomerNum+"条数据";
                    }
                    //重复id不为空
                    if(repeatIdStr!=""){
                        content = content + "<br>客户为第：" + repeatIdStr + "行数据，数据库已存在";
                    }
                    //失败id不为空
                    if(importFailIdStr!=""){
                        content = content + "<br>客户为第：" + importFailIdStr + "行数据导入失败";
                    }

                    $.alert({
                        title: '提示',
                        content: content,
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'btn-primary',
                                action: function () {
                                    $("#importCustomerFile").val("");
                                    $customerTable.bootstrapTable('refresh');
                                }
                            }
                        }
                    });
                    $('#importCustomerModal').modal('hide');
                    $("#importCustomerFile").val("");
                }else if(data.code == "IC0001"){
                    $.alert({
                        title: '提示',
                        content: data.message,
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'btn-primary',
                                action: function () {
                                    $("#importCustomerFile").val("");
                                }
                            }
                        }
                    });
                }else{
                    $.alert("导入失败");
                    $("#importCustomerFile").val("");
                }
            }),
            error:(function() {
                $.alert("导入出错！");
                $("#importCustomerFile").val("");
            })
        });
    } else {
        $.alert({
            title: '温馨提示',
            content: '请上传.xlsx文件！',
        });
    }
}*/

/**
 * 加载全部公司信息(全国公有池分配--公司下拉)
 */
function loadAllCompanyList() {
    $.getJSON("/company/getCompanyList", function (data) {
        if (data.code == '000000') {
            var companyOptionHtml = '';
            data.data.map(function (item) {
                companyOptionHtml += '<option value="' + item.companyId + '">' + item.companyName + '</option>';
            });
            $("#companySelectAll").html("");
            $('#companySelectAll').append(companyOptionHtml);
            $('#companySelectAll').selectpicker('refresh');
            loadPersonByCompanyId(data.data[0].companyId);
        }
    });
    // 当公司下拉改变时级联人员下拉信息
    $("select[id*='companySelectAll']").on("change", function () {
        loadPersonByCompanyId($(this).val());
    });
}

/**
 * 根据公司ID查询人员信息(加载分配人员下拉)
 * @param companyId
 */
function loadPersonByCompanyId(companyId) {
    $.getJSON("/account/getAccountListByCompanyId?companyId=" + companyId, function (data) {
        if (data.code == '000000') {
            var personDiv = '';
            data.data.map(function (item) {
                personDiv += '<div class="radio-box-my">' +
                    '<input name="people" type="radio" value="' + item.accountId + '"/>' +
                    item.userName +
                    '</div>';
            });
            $('.tip-content').html('');
            $('.tip-content').html(personDiv);
        }
    });
}

/**
 * 加载分公司信息(分公司公有池--分配)
 */
function loadBranchCompanyList(customerPoolId) {
    $.getJSON("/customer/selectBranchCompany?customerPoolId=" + customerPoolId, function (data) {
        if (data.code == '000000') {
            var companyOptionHtml = '';
            data.data.map(function (item) {
                companyOptionHtml += '<option value="' + item.companyId + '">' + item.companyName + '</option>';
            });
            $("#quanxianBox").html("");
            $('#quanxianBox').append(companyOptionHtml);
            $('#quanxianBox').selectpicker('refresh');
            $("#companySelectAll").html("");
            $('#companySelectAll').append(companyOptionHtml);
            $('#companySelectAll').selectpicker('refresh');
            loadPersonByCompanyId(data.data[0].companyId);
        }
    });
    // 当公司下拉改变时级联人员下拉信息
    $("select[id*='companySelectAll']").on("change", function () {
        loadPersonByCompanyId($(this).val());
    });
    // 当公司下拉改变时级联人员下拉信息
    $("select[id*='quanxianBox']").on("change", function () {
        $('#peopleSelectByCompanyId').html('');
        loadPersonByCompanyId($(this).val());
    })
}

/**
 * 分配选人--根据用户名查询其人员信息及公司名
 */
function selectPeopleByName() {
    var userName = $("#userName").val();//用户名
    var customerPoolId = $("#customerPoolId").val();//客户池ID
    var nature = $("#nature").val();//客户池类别
    if (nature == 1) {//客户池类别(全国公有池)
        $.getJSON("/customer/selectUserAndCompanyByName?userName=" + userName, function (data) {
            if (data.code == '000000') {
                let str = '';
                if (data.data.length) {
                    $('#noPeople').css('display', 'none');
                    data.data.map(function (item) {
                        str += '<li><span onclick="directSelectPeople(\'' + item.userName + '\',\'' + item.accountId + '\')">' + item.userName + '(' + item.companyName + ')</span></li>'
                    });
                    $("#dimSearch").html('');
                    $("#dimSearch").html(str);
                } else {
                    $("#dimSearch").html('<li id="noPeople"><span>暂无数据</span></li>');
                }
            }
        });
        return;
    }

    if (nature == 2) {//客户池类别(分公司公有池)
        $.getJSON("/customer/selectUserByPoolPermission?customerPoolId=" + customerPoolId + "&userName=" + userName, function (data) {
            if (data.code == '000000') {
                let str = '';
                if (data.data.length) {
                    $('#noPeople').css('display', 'none');
                    data.data.map(function (item) {
                        str += '<li><span onclick="directSelectPeople(\'' + item.userName + '\',\'' + item.accountId + '\')">' + item.userName + '（' + item.companyName + '）</span></li>'
                    });
                    $("#dimSearch").html('');
                    $("#dimSearch").html(str);
                } else {
                    $('#noPeople').css('display', 'block');
                }
            }
        });
    }
}

function directSelectPeople(userName, userId) {
    $('#choosedPeopleName').text(userName);
    $('#choosedPeopleId').val(userId);
}

/**
 * 客户--分配
 */
function distributeCustomer() {
    var distributeUserId = '';
    var customerId = $('#customerId').val();//客户ID
    var customerPoolId = $('#customerPoolId').val();//客户池ID

    var selectPeopleByCompany = $("input[name='people']:checked").val();//通过公司选人
    var selectPeopleByName = $('#choosedPeopleName').text();//通过人名选人
    var choosedPeopleId = $('#choosedPeopleId').val();
    if (selectPeopleByCompany && selectPeopleByName) {
        $.alert("客户只能分配给一个人,请重置选择");
        return;
    }
    if (selectPeopleByCompany) { //按公司选人
        distributeUserId = selectPeopleByCompany;
    }
    if (choosedPeopleId) { //按人名选人
        distributeUserId = choosedPeopleId;
    }
    if(!distributeUserId){
        $.alert("请选择一个人进行分配");
        return;
    }
    $.ajax({
        url: "/customerController/distributeCustomer",
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        dataType: "json",
        data: {
            distributeUserId: distributeUserId,
            customerId: customerId,
            customerPoolId: customerPoolId
        },
        success: function (data) {
            if (data.code == '000000') {//分配成功
                $.alert("操作成功！");
                $('#customerDistributeModal').modal('hide');
                $customerTable.bootstrapTable('refreshOptions', {pageNumber: 1});
            } else if (data.code == 'CP0002') {//超出客户池容量
                $.alert(data.message);
            } else if (data.code == 'CL0001') {//客户已锁定
                $.alert(data.message);
            } else {//操作失败
                $.alert('操作失败,请稍后再试');
            }
        },
        error: function () {
            $.alert('操作异常，请稍后再试!');
        }
    })
}

function resetDistributeModalData() {
    $("#dimSearch").html('');
    $('#choosedPeopleName').text('');
    $('#choosedPeopleId').val('');
    $('#userName').val('');
    $('#peopleSelectByCompanyId').find('input').prop('checked', false);
}

//  重置
function resetData(_this) {
    let searchForm = '';
    if($(_this).parents('#filterContent').context == document) {
        searchForm = $(_this);
    }else{
        searchForm = $(_this).parents('#filterContent');
    }

    // 重置表单内容
    searchForm.find('input[type="text"]').val('');
    searchForm.find('select').find('option:first').prop('selected', 'selected');
    // 刷新下拉菜单selectpicker控件
    searchForm.find('select').selectpicker('refresh');
    // 重置自定义筛选条件
    searchForm.find('.custom-group').find('input[type="checkbox"]').prop('checked', false);
    searchForm.find('.custom-group').removeClass('custom-active').find('select').removeAttr('disabled').selectpicker('refresh');
    searchForm.find('.custom-group').find('input[type="text"]').val('');

    // 点击重置按钮时，刷线table内容
    if($(_this).parents('#filterContent').context !== document) {
        searchCustomerTableList();
    }
}
